import { configureServer } from './serverMiddleware'
import { runCodeBlockPlugin } from './runCodeBlock'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import yaml from 'js-yaml'

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 读取YAML文件的函数
function readYamlFile(filePath) {
    try {
        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            return {}
        }

        // 读取文件内容
        const content = fs.readFileSync(filePath, 'utf8')
        if (!content.trim()) {
            return {}
        }

        // 使用js-yaml库解析YAML
        const config = yaml.load(content)
        return config || {}
    } catch (error) {
        console.error(`读取YAML文件出错: ${filePath} ${error.message}`)
        return {}
    }
}

const defaultRuntime = {
    js: { cmd: 'node', ext: '', args: [] },
    javascript: { cmd: 'node', ext: 'js', args: [] },
    ts: { cmd: 'esno', ext: '', args: [] },
    typescript: { cmd: 'esno', ext: 'ts', args: [] },
    py: { cmd: 'python', ext: '', args: [] },
    sh: { cmd: 'sh', ext: '', args: [] }
}

class RunCode {
    vitePlugin
    mdConfig

    constructor(runtimeConf = {}) {
        // 读取runtimeConfig.yaml文件
        const runtimeConfigPath = path.join(__dirname, 'runtimeConfig.yaml')
        const yamlConfig = readYamlFile(runtimeConfigPath)
        console.log("%c Line:52 🍰 yamlConfig", "color:#fca650", yamlConfig);

        // 合并配置: defaultRuntime < runtimeConfig.yaml < 传入的runtimeConf
        const finalConfig = Object.assign({}, defaultRuntime, yamlConfig, runtimeConf)
        console.log("%c Line:55 🧀 finalConfig", "color:#3f7cff", finalConfig);

        this.mdConfig = (md) => {
            if (process.env.NODE_ENV !== 'development') return undefined
            runCodeBlockPlugin(md, finalConfig)
        }
        this.vitePlugin = () => {
            if (process.env.NODE_ENV !== 'development') return undefined
            return {
                name: 'run-code-block-client-script',
                configureServer: (server) => {
                    configureServer(server, finalConfig)
                }
            };
        };
    }
}

export default RunCode
